<template>
  <div class="query-results h-full flex flex-col overflow-hidden">
    <div v-if="executing" class="executing-state flex-1 flex items-center justify-center">
      <div class="flex items-center">
        <div class="loading-spinner mr-2"></div>
        <span class="text-gray-600">正在执行查询...</span>
      </div>
    </div>
    
    <div v-else-if="result" class="result-content h-full flex flex-col flex-1 overflow-hidden">
      <div v-if="result.error" class="error-result p-4">
        <el-alert
          :title="result.error"
          type="error"
          :closable="false"
          show-icon
        />
      </div>
      
      <div v-else class="success-result h-full flex flex-col flex-1 overflow-hidden">
        <!-- 结果统计和操作 -->
        <div class="result-stats py-2 px-4 flex items-center justify-between border-b border-gray-200 flex-shrink-0">
          <div class="stats-left flex items-center space-x-4">
            <span class="text-sm text-gray-600">
              共 {{ result.rowCount || 0 }} 行
            </span>
            <span class="text-sm text-gray-500">
              耗时: {{ formatDuration(result.executeTime) }}
            </span>
          </div>
          <div class="stats-right flex items-center space-x-2">
            <el-button size="small" type="primary" @click="copyToClipboard">
              <el-icon><DocumentCopy /></el-icon>
              复制
            </el-button>
            <el-dropdown trigger="click" @command="handleExport">
              <el-button size="small">
                <span class="flex items-center">
                  <el-icon class="mr-1"><Download /></el-icon>
                  导出
                  <el-icon class="ml-1"><ArrowDown /></el-icon>
                </span>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="csv">CSV格式</el-dropdown-item>
                  <el-dropdown-item command="xlsx">Excel格式</el-dropdown-item>
                  <el-dropdown-item command="json">JSON格式</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>
        
        <!-- 数据表格 -->
        <div v-if="result.data && result.data.length > 0" class="result-table flex-1 overflow-hidden flex flex-col">
          <!-- 使用新的DatabaseTable组件 -->
          <database-table
            ref="databaseTable"
            :data="result.data"
            :columns="tableColumns"
            :editable="false"
            :show-toolbar="false"
            :show-status-bar="false"
            @column-resize="handleColumnResize"
            @row-resize="handleRowResize"
            class="flex-1"
          />
        </div>
        
        <!-- 无数据 -->
        <div v-else class="no-data text-center py-8 flex-1 flex items-center justify-center">
          <div>
            <el-icon class="text-4xl text-gray-400 mb-2"><DocumentRemove /></el-icon>
            <p class="text-gray-500">查询未返回数据</p>
          </div>
        </div>
      </div>
    </div>
    
    <div v-else class="no-result text-center py-8 flex-1 flex items-center justify-center">
      <div>
        <el-icon class="text-4xl text-gray-400 mb-2"><Document /></el-icon>
        <p class="text-gray-500">请输入SQL查询并点击执行</p>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, watch, computed, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { DocumentCopy, Download, ArrowDown, DocumentRemove, Document } from '@element-plus/icons-vue'
import DatabaseTable from '../../common/DatabaseTable.vue'

const props = defineProps({
  result: {
    type: Object,
    default: null
  },
  executing: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['export', 'column-resize', 'row-resize'])

// 组件引用
const databaseTable = ref(null)

// 处理列宽调整
const handleColumnResize = (event) => {
  console.log('QueryResults - 列宽调整事件:', event)
  console.log(`列 ${event.column} 的宽度调整为 ${event.width}px`)
  
  // 保存列宽设置（使用查询结果的唯一标识）
  const columnWidths = JSON.parse(localStorage.getItem('query-column-widths') || '{}')
  const queryId = 'query-result' // 可以考虑使用更唯一的标识
  if (!columnWidths[queryId]) columnWidths[queryId] = {}
  
  if (typeof event.column === 'number' && props.result.columns[event.column]) {
    const columnField = props.result.columns[event.column].name
    columnWidths[queryId][columnField] = event.width
    localStorage.setItem('query-column-widths', JSON.stringify(columnWidths))
    console.log(`保存查询结果列宽: ${columnField} = ${event.width}`)
  }
  
  emit('column-resize', event)
}

// 处理行高调整
const handleRowResize = (event) => {
  console.log('QueryResults - 行高调整事件:', event)
  console.log(`行 ${event.row} 的高度调整为 ${event.height}px`)
  
  // 可以选择性地保存行高设置
  emit('row-resize', event)
}

// 计算表格列配置
const tableColumns = computed(() => {
  if (!props.result?.columns || props.result.columns.length === 0) {
    return []
  }
  
  console.log('QueryResults - 原始结果:', props.result)
  console.log('QueryResults - 列信息:', props.result.columns)
  console.log('QueryResults - 数据示例:', props.result.data?.[0])
  
  return props.result.columns.map(col => {
    // col 可能是字符串（后端直接返回）或对象（经过store转换）
    const colName = typeof col === 'string' ? col : col.name
    const colType = typeof col === 'object' ? col.type : 'text'
    
    // 根据列类型智能设置宽度
    let width = 120
    
    // 分析第一行数据来推断更合适的宽度
    if (props.result.data && props.result.data.length > 0) {
      const sampleValue = props.result.data[0][colName]
      if (sampleValue !== null && sampleValue !== undefined) {
        const valueStr = String(sampleValue)
        const estimatedWidth = Math.min(Math.max(valueStr.length * 8 + 20, 60), 400)
        width = estimatedWidth
      }
    }
    
    // 根据列名特征调整
    const lowerColName = colName.toLowerCase()
    if (lowerColName === 'id' || lowerColName.endsWith('_id')) {
      width = Math.min(width, 80)
    } else if (lowerColName.includes('name') || lowerColName.includes('title')) {
      width = Math.max(width, 150)
    } else if (lowerColName.includes('description') || lowerColName.includes('content')) {
      width = Math.max(width, 250)
    } else if (lowerColName === 'count' || lowerColName === 'sum' || lowerColName === 'avg') {
      width = 100
    }
    
    return {
      field: colName,
      title: colName,
      width: width,
      type: colType,
      align: ['number', 'integer', 'float', 'decimal'].includes(colType) ? 'right' : 'left'
    }
  })
})

// 格式化时间
const formatDuration = (duration) => {
  if (!duration) return '0ms'
  
  if (typeof duration === 'number') {
    if (duration < 1000) {
      return `${Math.round(duration)}ms`
    } else {
      return `${(duration / 1000).toFixed(2)}s`
    }
  }
  
  return String(duration)
}

// 复制到剪贴板
const copyToClipboard = async () => {
  if (!props.result?.data || props.result.data.length === 0) {
    ElMessage.warning('没有可复制的数据')
    return
  }
  
  try {
    // 复制所有数据
    const headers = props.result.columns.map(col => col.name)
    const rows = props.result.data.map(row => headers.map(header => {
      const value = row[header]
      return value === null ? 'NULL' : String(value)
    }))
    
    // 创建CSV格式的文本
    const csvContent = [
      headers.join('\t'),
      ...rows.map(row => row.join('\t'))
    ].join('\n')
    
    await navigator.clipboard.writeText(csvContent)
    ElMessage.success('数据已复制到剪贴板')
  } catch (error) {
    console.error('复制失败:', error)
    ElMessage.error('复制失败')
  }
}

// 导出处理
const handleExport = (format) => {
  if (!props.result?.data || props.result.data.length === 0) {
    ElMessage.warning('没有可导出的数据')
    return
  }
  
  emit('export', { format, data: props.result.data, columns: props.result.columns })
}
</script>

<style scoped>
.query-results {
  display: flex;
  flex-direction: column;
  height: 100%;
  width: 100%;
  overflow: hidden;
  position: relative;
}

.success-result,
.result-content,
.result-table {
  display: flex;
  flex-direction: column;
  flex: 1;
  width: 100%;
  height: 100%;
  overflow: hidden;
  position: relative;
}

.result-stats {
  flex-shrink: 0;
  background-color: #f9fafb;
  z-index: 1;
  height: 40px;
}

.loading-spinner {
  width: 20px;
  height: 20px;
  border: 2px solid #e5e7eb;
  border-top: 2px solid #3b82f6;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}
</style> 